/**
 * calculator
 *
 * @author : tzy
 * @Date : 2021-03-22
 * @Description:
 **/

package com.tang.calculator.functions;

import com.tang.calculator.context.CalculateContext;
import com.tang.calculator.symbols.StringValueSymbol;
import com.tang.calculator.symbols.ValueSymbol;
import com.tang.calculator.symbols.ValueSymbolFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.util.Stack;

@Component
public class StrCatFunction extends AbstractFunction {

    @Autowired
    ValueSymbolFactory valueSymbolFactory;

    @Override
    public String getFunctionName() {
        return "strCat";
    }

    @Override
    public void run(CalculateContext context, ValueSymbol... args) {
        Stack<ValueSymbol> valueStack = context.getValueStack();

        if (args != null && args.length > 0) {
            StringBuilder sb = new StringBuilder();
            for (Object arg : args) {
                if (arg instanceof StringValueSymbol) {
                    StringValueSymbol valueSymbol = (StringValueSymbol) arg;
                    sb.append(valueSymbol.getName());
                } else if (arg instanceof ValueSymbol) {
                    ValueSymbol valueSymbol = (ValueSymbol) arg;
                    sb.append(resolveDecimal(valueSymbol.getValue().toString()));
                }
            }
            valueStack.push(valueSymbolFactory.createString(sb.toString()));
        }
    }

    private String resolveDecimal(String value) {
        if (!StringUtils.isEmpty(value)) {
            return value.replaceAll("(0+)|(\\.0+)$", "");
        }
        return value;
    }
}
